﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using Microsoft.Xna.Framework;
using Tomahawk.Runtime.Logic.UI;
using Tomahawk.Runtime.Canvas.Sprite;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;

namespace Tomahawk.Runtime.Timeline
{
    public class NormalMapEffectTrack : SpriteEffectTrack
    {
        [XmlElement("LightDirX")]
        public string lightDirX = "";

        [XmlElement("LightDirY")]
        public string lightDirY = "";

        [XmlElement("LightDirZ")]
        public string lightDirZ = "";

        [XmlElement("Normalmap")]
        public string normalMap = "";

        [XmlElement("LightColor")]
        public Color lightColor = Color.White;

        [XmlElement("AmbientColor")]
        public Color ambientColor = Color.Black;

        private bool firstUpdate = true;
        private Vector3 lightDir = Vector3.Zero;
        private Curve curvelightDirX = new Curve();
        private Curve curvelightDirY = new Curve();
        private Curve curvelightDirZ = new Curve();
        private Texture normalMapTexture = null;

        public NormalMapEffectTrack() : base() { }

        public NormalMapEffectTrack(string name) : base(name) { }

        protected override string GetEffectFile()
        {
            return @"Tomahawk.Content\SpriteEffects\NormalMapEffect";
        }

        protected override void OnLoadEffectParameters(Effect effect)
        {
            if (firstUpdate)
            {
                effect.Parameters["NormalTexture"].SetValue(normalMapTexture);
                effect.Parameters["LightColor"].SetValue(lightColor.ToVector3());
                effect.Parameters["AmbientColor"].SetValue(ambientColor.ToVector3());
                firstUpdate = false;
            }

            effect.Parameters["LightDirection"].SetValue(lightDir);
        }

        protected override bool OnLoad(GraphicsDevice graphics, ContentManager contentManager)
        {
            curvelightDirX = LoadCurve(contentManager, lightDirX);
            curvelightDirY = LoadCurve(contentManager, lightDirY);
            curvelightDirZ = LoadCurve(contentManager, lightDirZ);
            normalMapTexture = contentManager.Load<Texture>(normalMap);

            return base.OnLoad(graphics, contentManager);
        }

        public override void SortKeys() { }

        public override bool Update(float time)
        {
            if (curvelightDirX == null || curvelightDirY == null || curvelightDirZ == null)
            {
                return false;
            }

            lightDir.X = curvelightDirX.Evaluate(time);
            lightDir.Y = curvelightDirY.Evaluate(time);
            lightDir.Z = curvelightDirZ.Evaluate(time);

            return true;
        }
    }
}
